package eu.vconect.orch.servlets;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.google.gson.Gson;

import eu.vconect.orch.HangoutSession;


/**
 * Servlet implementation class OrchestrationRequest
 */
@WebServlet("/cut")
public class OrchestrationRequest extends HttpServlet {
       
	private static final long serialVersionUID = -5041888213808839343L;
	private static Logger LOG = Logger.getLogger(OrchestrationRequest.class);	
	
	/**
     * @see HttpServlet#HttpServlet()
     */
    public OrchestrationRequest() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Map<String, Object> jsonResp = new HashMap<String, Object>();
		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Access-Control-Allow-Origin", "*");
		
		try {
			// log the request parameters
			for ( int i = 0; i < ReqParams.values().length; i++ )
				if ( request.getParameter(ReqParams.values()[i].toString()) != null )
					LOG.debug(ReqParams.values()[i] + " = " + request.getParameter(ReqParams.values()[i].toString()));
			
			// check if ReqParam.hangoutUrl parameter is set
			if ( request.getParameter(ReqParams.hangoutUrl.toString()) == null || 
					request.getParameter(ReqParams.participantId.toString()) == null)
				//TODO Specialize the exception
				throw new Exception("The required [" + ReqParams.hangoutUrl + "] parameter is not set.");
			
			// get the hangout session instance
			HangoutSession hangout = HangoutSession.instance(request.getParameter(ReqParams.hangoutUrl.toString()));			
			jsonResp.put("cutTo", hangout.getOrchestrator().cutTo(request.getParameter(ReqParams.participantId.toString())));			
		} catch ( Exception e ) {
			jsonResp.put("error", e.getMessage());
			LOG.error(e.getMessage());
			request.setAttribute ("javax.servlet.jsp.jspException", e);
			e.printStackTrace();
		} finally {
			// return the JSON 
			response.getWriter().write(new Gson().toJson(jsonResp));			
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
